package com.wuwie.article.service.impl;

import com.wuwie.article.entity.Comment;
import com.wuwie.article.service.CommentService;
import com.mongodb.client.result.DeleteResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.LookupOperation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private MongoTemplate mongoTemplate;


    //全查询
    @Override
    public List<Comment> select() {
        LookupOperation lookupOperation= LookupOperation.newLookup().from("subComment").localField("_id").foreignField("parentid").as("subComments");
        Aggregation aggregation=Aggregation.newAggregation(lookupOperation);
        List<Comment> results = mongoTemplate.aggregate(aggregation,"comment", Comment.class).getMappedResults();
        return results;
    }

    //删除
    @Override
    public long delcomment(String id) {
        Query query = new Query(Criteria.where("id").is(id));
        DeleteResult remove = mongoTemplate.remove(query, Comment.class);
        long count = remove.getDeletedCount();
        return count;
    }

    //添加
    @Override
    public Integer addcomment(Comment comment) {
        Comment insert = mongoTemplate.insert(comment);
        if (insert == null){
          return 1;
        }
        return 0;
    }
}
